# -*- coding: utf-8 -*-
from functools import partial

from sqlalchemy.exc import IntegrityError

from common.lottery.cyclical.abstract import activity as base
from common.utils.decorator import sql_wrapper
from common.lottery import LOTTERY_TYPE

fullfill_result = sql_wrapper(
    partial(base.fullfill_result, LOTTERY_TYPE.TC_PLS))


get_latest_term = sql_wrapper(
    partial(base.get_latest_term, LOTTERY_TYPE.TC_PLS))


get_activity_by_term = sql_wrapper(
    partial(base.get_activity_by_term, LOTTERY_TYPE.TC_PLS))


stop_term = sql_wrapper(
    partial(base.stop_term, LOTTERY_TYPE.TC_PLS))


create_new_term = sql_wrapper(
    partial(base.create_new_term, LOTTERY_TYPE.TC_PLS))


get_stats_by_term = sql_wrapper(
    partial(base.get_stats_by_term, LOTTERY_TYPE.TC_PLS))


get_activity_stats = sql_wrapper(
    partial(base.get_activity_stats, LOTTERY_TYPE.TC_PLS))


def calc_miss(trend, save, number, last_stats):
    ''' 计算遗漏值，其他时时彩与此类似，直接引用
    '''
    pass


@sql_wrapper
def insert_stats(term, number, last_stats):
    """
    至少每一個號碼都要開過一次，才會真正存進db，如果要重新整理一次，使用tools/generate_cyclical_trend.py
    期號如果不夠，使用crawler.py {date}增加爬取的期數。
    term: 期號(str)
    number: 開獎號碼(str)
    last_stats: 上一期(model.activity.Trend)
    trend: 這一期(model.activity.Trend)
    save: 是否儲存(bool)
    """
    trend, save = base.generate_trend(
        LOTTERY_TYPE.TC_PLS, term, number, last_stats)
    if save:
        try:
            trend.save()
        except IntegrityError:
            pass
    return trend
